//
//  LJStatus.swift
//  LJWeibo
//
//  Created by Raymond on 15/12/21.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit
import SDWebImage

class LJStatus: NSObject {

    // MARK: - 属性
    /// 创建时间
    var created_at: String?
    
    /// 微博ID
    var id: Int = 0
    
    /// 微博内容
    var text: String?
    
    /// 微博来源
    var source: String?
    
    /// 微博配图
    var pic_urls: [[String : AnyObject]]? {
        didSet {
            let count = pic_urls?.count ?? 0
            if count == 0 {
                // 没有配图
                return
            }
            
            // 有配图则将字典数组转化为URL数组
            storePictureURLs = [NSURL]()
            // 大图数组
            largePictureURLs = [NSURL]()
            for dict in pic_urls! {
                let urlString  = dict["thumbnail_pic"] as! String

                let url = NSURL(string: urlString)!
                
                // 获取大图的URL地址
                let largerURLString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                let largeURL = NSURL(string: largerURLString)
                
                largePictureURLs?.append(largeURL!)
                
                storePictureURLs?.append(url)
            }
        }
    }
    
    /// 微博配图（url）原创微博的配图
    var storePictureURLs: [NSURL]?
    
    /// 微博大图的URL地址
    var largePictureURLs: [NSURL]?
    
    /// 微博配图
    var pictureURLs: [NSURL]?{
        return retweeted_status == nil ? storePictureURLs : retweeted_status?.storePictureURLs
    }
    
    /// 微博大图
    var largePictureURLS: [NSURL]? {
        return retweeted_status == nil ? largePictureURLs : retweeted_status?.largePictureURLs
    }
    
    /// 转发数
    var reposts_count: Int = 0
    
    /// 评论数
    var comments_count: Int = 0
    
    /// 点赞数
    var attitudes_count: Int = 0
    
    /// 用户模型
    var user: LJUser?
    
    /// 转发的微博数据
    var retweeted_status: LJStatus?
    
    /// 行高
    var rowHeight: CGFloat?
    
    /// 返回重用表示
    func cellID() -> String {
        return retweeted_status == nil ? LJStatusCellReuseIdentifier.StatusNormalCell.rawValue : LJStatusCellReuseIdentifier.StatusForwardCell.rawValue
    }
    
    /// MARK: - 字典转模型方法
    init(dict: [String : AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    // 找不到对应的属性时调用该方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    // 在该方法里将服务器返回的用户字典转模型  
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String : AnyObject]{
                // 字典转模型
                let user = LJUser(dict: dict)
                // 赋值
                self.user = user
            }
            // 一定要返回
            return
        }
        
        if key == "retweeted_status" {
            if let dict = value as? [String : AnyObject]{
                let retweeted_status = LJStatus(dict: dict)
                self.retweeted_status = retweeted_status
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    
    /// MARK: - 实现despcription方法
    override var description: String{
        let pros = ["created_at", "id", "text", "source", "pic_urls", "reposts_count", "comments_count", "attitudes_count", "user", "retweeted_status"]
        // 会根据字典中的键到self中找对应值并返回字典
        let dict = self.dictionaryWithValuesForKeys(pros)
        
        return "\n\t微博模型:\(dict)"
    }
    
    
    
    ///MARK: - 加载数据的方法
    class func loadStatus(since_id: Int, max_id: Int, finished: (statuses: [LJStatus]?, error: NSError?) -> ()){
        LJNetworkTool.shareInstance.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
            if error != nil || result == nil{
                finished(statuses: nil, error: error)
                return
            }
            
            // 没有错误或者结果不为空时调用
            // 判断数字中是否有statuses数组
            if let array = result?["statuses"] as? [[String : AnyObject]]{
                // 创建存放模型的数组
                var statuses = [LJStatus]()
                
                // 遍历数组中的数组中的字典
                for dict in array{
                    // 字典转模型
                    let status = LJStatus(dict: dict)
                    // 添加到数组中
                    statuses.append(status)
                }
                // 回调
                //                finished(statuses: statuses, error: nil)
                // 下载图片
                cacheWebImage(statuses, finished: finished)
                
            }else{
                
                finished(statuses: nil, error: error)
            }
        }
    }
    
    class func cacheWebImage(statuses: [LJStatus], finished: (statuses: [LJStatus]?, error: NSError?) -> ()) {
        // 记录下载图片的大小
        var length = 0.0
        // 创建任务组
        let group = dispatch_group_create()
        // 遍历所有模型
        for status in statuses {
            guard let urls = status.pictureURLs else {
                // 没有图片缓存,跳到下一个
                continue
            }
            // 判断是否指有一张图片
            if urls.count == 1 {
                let url = urls[0]
                // 进入组
                dispatch_group_enter(group)
                // 下载图片
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    // 离开组
                    dispatch_group_leave(group)
                    if error != nil {
                        print("缓存图片失败\(url)")
                        return
                    }
                    // 计算图片大小
                    let data = UIImagePNGRepresentation(image)!
                    length += Double(data.length)
                })
            }
        
        }
        // 结束所有下载图片任务后调用
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            print("图片大小：\(length)")
            // 回调
            finished(statuses: statuses, error: nil)
        })
    }
}
